package com.sakila.jaas;

import java.util.ArrayList;
import java.util.List;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import com.sakila.pojo.Member;
import com.sakila.service.MemberService;
import com.sakila.vo.MyMember;

public class MemberAuthentication implements UserDetailsService{

	private final MemberService memberService;
	
	public MemberAuthentication(MemberService memberService) {
		this.memberService = memberService;
	}

	@Override
	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException {
		Member member = memberService.findByUsername(username);
		if(member == null){
			throw new UsernameNotFoundException("User '" + username + "' not found.");
		}
		List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
		member.getRoles().forEach(
						role -> authorities.add(new SimpleGrantedAuthority(role.getRole()))
		);
		/*for(Role role : member.getRoles()){
			authorities.add(new SimpleGrantedAuthority(role.getRole()));
		}*/
		return new MyMember(member.getUsername(), 
							member.getPassword(), 
							authorities, member);
	}

}
